/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GuiVeiculo.java
 *
 * Created on 22/11/2011, 21:02:20
 */

package GUI;
import java.util.Vector;
import tp1POO.Persistencia.GerenciadorObjetos;
import tp1POO.Modelo.*;
import tp1POO.Verifica;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import tp1POO.GestorLog;
import tp1POO.Persistencia.Pesquisa;
/**
 *
 * @author matheus
 */
public class GuiVeiculo extends javax.swing.JFrame {
    String msg="";
    /** Creates new form GuiVeiculo */
    public GuiVeiculo() {
        initComponents();
        carregaListaTipo();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPVeiculo = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        campoPlaca = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        campoMarca = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        campoModelo = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        campoCor = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        campoOp = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        campoObs = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable = new javax.swing.JTable();
        jBCancel = new javax.swing.JButton();
        jBOk = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Cadastrar Veículo");

        jPVeiculo.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados do Veículo"));

        jLabel1.setText("Placa :");

        jLabel2.setText("Marca :");

        jLabel3.setText("Modelo :");

        jLabel4.setText("Cor :");

        jLabel5.setText("Opcionais :");

        jLabel6.setText("Observações :");

        jLabel7.setText("Selecione um tipo de Locação :");

        jTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nome", "Preço por Quilômetro", "Taxa Base"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTable);

        javax.swing.GroupLayout jPVeiculoLayout = new javax.swing.GroupLayout(jPVeiculo);
        jPVeiculo.setLayout(jPVeiculoLayout);
        jPVeiculoLayout.setHorizontalGroup(
            jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPVeiculoLayout.createSequentialGroup()
                .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPVeiculoLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(campoOp, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)
                            .addComponent(campoObs, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)))
                    .addGroup(jPVeiculoLayout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(campoPlaca, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
                            .addComponent(campoMarca, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(campoModelo)
                            .addComponent(campoCor, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)))
                    .addGroup(jPVeiculoLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel7))
                    .addGroup(jPVeiculoLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPVeiculoLayout.setVerticalGroup(
            jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPVeiculoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(campoMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(campoPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoCor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(campoOp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(campoObs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
                .addContainerGap())
        );

        jBCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/icoErro.gif"))); // NOI18N
        jBCancel.setText("Fechar");
        jBCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCancelActionPerformed(evt);
            }
        });

        jBOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/certo.gif"))); // NOI18N
        jBOk.setText("Ok");
        jBOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBOkActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPVeiculo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jBOk)
                        .addGap(42, 42, 42)
                        .addComponent(jBCancel)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jBCancel, jBOk});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jPVeiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBOk)
                    .addComponent(jBCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jBCancel, jBOk});

        pack();
    }// </editor-fold>//GEN-END:initComponents


    private void carregaListaTipo () {
        Tipo tipo = new Tipo(" ");
        Vector<ObjetoPOO> obj = GerenciadorObjetos.obterInstancia().obterObjs(tipo);
        DefaultTableModel modelo = (DefaultTableModel)jTable.getModel();
        
        if (obj.size()!=0) {
            for (int i=0;i<obj.size();i++) {
                tipo = (Tipo)obj.get(i);
                modelo.addRow( new String [] {tipo.getNome(),String.valueOf(tipo.getPrecoQuilometro()),String.valueOf(tipo.getTaxaBase())} );

            }
        }
    }


    private Tipo criaTipo () {
        String aux="",nome="";
        float quilo=0,taxaBase=0;
        int indice = jTable.getSelectedRow();

        for (int i=0;i<jTable.getColumnCount();i++) {
            aux = (String)jTable.getValueAt(indice, i);
            if (i==0) {
                nome = aux;
            }
            else if (i==1)   {
                quilo = Float.parseFloat(aux);
            }
            else if (i==2) {
                taxaBase = Float.parseFloat(aux);
            }
        }

        Tipo tipo = new Tipo(nome,taxaBase,quilo);
        return tipo;
    }



    private boolean erroVeiculo () {
        boolean erro = false;
        
        erro = !Verifica.placaVeiculo(campoPlaca.getText()).isEmpty()||campoCor.getText().isEmpty()||campoMarca.getText().isEmpty()||campoModelo.getText().isEmpty()||jTable.getSelectedRow()==-1;//||jLTipos.isSelectionEmpty();
        if (campoMarca.getText().isEmpty()) {
            msg = msg + "ERRO : Marca Inválida!\n";
        }
        if (campoModelo.getText().isEmpty()) {
            msg = msg + "ERRO : Modelo Inválida!\n";
        }
        if (campoCor.getText().isEmpty()) {
            msg = msg + "ERRO : Cor Inválida!\n";
        }
        if (jTable.getSelectedRow() == -1) {
            msg = msg + "ERRO : Nenhum tipo foi selecionado!\n";
        }
        msg = msg + Verifica.placaVeiculo(campoPlaca.getText());
        if (erro) {
            JOptionPane.showMessageDialog(jPVeiculo,msg, "Error", JOptionPane.ERROR_MESSAGE);
        }
        msg = "";

        return erro;
    }









    



    private void jBOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBOkActionPerformed
                Veiculo veiculo = null;
		String placa;

                if (!erroVeiculo()) {
                    placa = campoPlaca.getText();
                    veiculo = new Veiculo(placa);
                    veiculo.setMarca(campoMarca.getText());
                    veiculo.setModelo(campoModelo.getText());
                    veiculo.setCor(campoCor.getText());
                    veiculo.setObservacoes(campoObs.getText());
                    veiculo.setOpcionais(campoOp.getText());
                    Tipo tipo = criaTipo();
                    veiculo.setTipoVeiculo(tipo);
                    GerenciadorObjetos.obterInstancia().salvarObj(veiculo);
                    campoCor.setText("");
                    campoMarca.setText("");
                    campoModelo.setText("");
                    campoObs.setText("");
                    campoOp.setText("");
                    campoPlaca.setText("");
                    GestorLog.obterInstancia().inserirMsgLog(GuiCreator.obterInstancia().getGuiFuncionalidades().getFuncionario().getCpf()+
                        " - Veículo cadastrado com sucesso!\n\tMarca : "+veiculo.getMarca()+"\n\tModelo : "+
                        veiculo.getModelo()+"\n\tCor : "+veiculo.getCor()+"\n\tPlaca : "+veiculo.getPlaca());
                    JOptionPane.showMessageDialog(jPVeiculo,"Veículo cadastrado com Sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
                }		
    }//GEN-LAST:event_jBOkActionPerformed

    private void jBCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCancelActionPerformed
        GestorLog.obterInstancia().inserirMsgLog("Funcionalidade de Adicionar veículos foi fechada("+GuiCreator.obterInstancia().getGuiFuncionalidades().getFuncionario().getCpf()+")");
        GuiCreator.obterInstancia().removerGuiVeiculo();
    }//GEN-LAST:event_jBCancelActionPerformed


















    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GuiVeiculo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField campoCor;
    private javax.swing.JTextField campoMarca;
    private javax.swing.JTextField campoModelo;
    private javax.swing.JTextField campoObs;
    private javax.swing.JTextField campoOp;
    private javax.swing.JTextField campoPlaca;
    private javax.swing.JButton jBCancel;
    private javax.swing.JButton jBOk;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPVeiculo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable;
    // End of variables declaration//GEN-END:variables

}
